#include "common.h"
char name_music[200][200] = {"./music/nndsn.mp3", "./music/brjym.mp3", "./music/wmdr.mp3"};
int idex = 2, nums = 3;
int status = 0;
void music(int op)
{

    if (nums == 0)
    {
        perror("当前无music");
    }
    char cmd[100] = "madplay -Q ";
    char tmp[100] = "";
    switch (op)
    {
    case 1:
        if(status!=OFF)system("killall madplay");
        idex = (idex + 1) % nums;

        strcpy(tmp, cmd);
        strcat(tmp, name_music[idex]);
        strcat(tmp, " &");
        printf("%s\n", tmp);
        system(tmp);
        status = ON;
        break;
    case 2:
        if(status!=OFF)system("killall madplay");
        idex = (idex - 1 + nums) % nums;
        strcpy(tmp, cmd);
        strcat(tmp, name_music[idex]);
        strcat(tmp, " &");
        printf("%s\n", tmp);
        status = ON;
        system(tmp);
        break;
    case 3:
        system("killall -STOP madplay");
        printf("killall -STOP madplay");
        status = STOP;
        break;
    case 4:
        if (status == OFF)
        {
            strcpy(tmp, cmd);
            strcat(tmp, name_music[idex]);
            strcat(tmp, " &");
            printf("%s\n", tmp);
            status = ON;
            system(tmp);
        }
        else if(status==STOP)
        {
            status = ON;
            system("killall -CONT madplay");
            printf("killall -CONT madplay");
        }
        break;
    case 5:
        system("killall madplay");
        printf("killall madplay");
        status = OFF;
        break;
    }
}
int is_mp3_file(const char *filename)
{
    size_t len = strlen(filename);
    return len >= 4 && strcmp(filename + len - 4, ".mp3") == 0;
}
void get_music(char *name)
{
    nums = 0;
    DIR *dir;
    struct dirent *entry;
    struct stat file_stat;
    if (name != NULL)
        dir = opendir(name);
    else
        dir = opendir("./music");
    if (dir == NULL)
    {
        perror("opendir");
        exit(EXIT_FAILURE);
    }

    // 遍历目录
    while ((entry = readdir(dir)) != NULL)
    {
        if (stat(entry->d_name, &file_stat) == -1)
        {
            perror("stat");
            exit(EXIT_FAILURE);
        }

        // 判断是否为文件且文件名以.mp3结尾
        if (S_ISREG(file_stat.st_mode) && is_mp3_file(entry->d_name))
        {
            // printf("%s\n", entry->d_name);
            strcpy(name_music[nums], "");
            if (name != NULL)
                strcpy(name_music[nums], name);
            strcat(name_music[nums++], entry->d_name);
        }
    }
    for (int i = 0; i < nums; i++)
    {
        printf("%s\n", name_music[i]);
    }
}